package com.base.myproject.client.HR.Training;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.HR.bcode.BcodeSelectDialog;
import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseTreeStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.base.myproject.client.ui.celleditor.BaseComboBoxX;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoader;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.CheckColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckCascade;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckNodes;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Label;

public class Training_Record extends BaseJDBCPanel{
	
	String treeDepId = null;                       //将当前树形结构中选中的部门id保存
	String treeDepName = null;                     //将当前树形结构中选中的部门name保存
	TreePanel<TreeNodeModelData> treepanel = null;
	BaseComboBoxForm<BaseModelData> sectionCode = new BaseComboBoxForm<BaseModelData>("id","name","SystemInfo","where name is not null and id is not null and len(id)=(select max(len(id)) from systeminfo)",true);
	BaseComboBoxForm<BaseModelData> typeCode = new BaseComboBoxForm<BaseModelData>("typeCode","typeName","hr_TrainingTypeDefine","",true);
	BaseComboBoxForm<BaseModelData> typeRenert = new BaseComboBoxForm<BaseModelData>("typeCode","typeName","hr_TrainingTypeDefine","",true);
	BaseComboBoxForm<BaseModelData> bcode = new BaseComboBoxForm<BaseModelData>("a.bcode","a.bname","bcode_job b, bcode a","where a.bcode = b.bcode and employstatus='在职'",true);
	BaseComboBoxX trainingcontent = new BaseComboBoxX ("content","hr_TrainingType_content","");
	Date date1;
	Date date2;
	String results = null;
	String bcode2 = Env.getEnvbcode();
	PagingToolBar toolBar1 = null;
	PagingToolBar toolBar2 = null;
	
	public Training_Record(){
		String sql = "select substring('id like '''+replace(permissionsbcode,';','%'' or id like '''),9," +
		"len('id like '''+replace(permissionsbcode,';','%'' or id like '''))-21) as result from" +
		" busipermissions where bcode = '"+bcode2+"' and busicode = 8010";
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService2.getDataSet(sql, new AsyncCallback<DataSet>(){
		@Override
			public void onFailure(Throwable caught) {	
			}
			@Override
			public void onSuccess(DataSet result) {  
			   results = result.getValue(0, "result");
			   init();
			}
		});
	}
	
	public void init(){
		initWidget();
		registerMainStore(store2);
		registerStore(store2);
		this.grid2.addListener(Events.OnClick, getListener());
	}
	
	public void complete(){
		super.complete();
	}
	
	public void initWidget(){
		toolBar1 = new PagingToolBar(12);
		toolBar2 = new PagingToolBar(12);
		HorizontalPanel cp = new HorizontalPanel();
		VerticalPanel vp2 = new VerticalPanel();	
		vp2.setSpacing(3);
		VerticalPanel vp3 = new VerticalPanel();
		vp3.setSpacing(3);
		HorizontalPanel hp = new HorizontalPanel();
		
		BorderLayoutData northData = new BorderLayoutData(LayoutRegion.WEST, 200);  
		northData.setCollapsible(true);  
		northData.setFloatable(true);  
		northData.setHideCollapseTool(true);  
		northData.setSplit(true);  
		northData.setMargins(new Margins(5, 5, 0, 0));
		
		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);  
	    centerData.setMargins(new Margins(5,0,0,0));  
		
		vp2.add(this.createAdd());
		ContentPanel panel3 = new ContentPanel();
		panel3.setHeaderVisible(false);
		panel3.add(this.getGrid2());
		panel3.setBottomComponent(toolBar1);
		panel3.setBorders(false);
		vp2.add(panel3);
		
		ContentPanel panel2 = new ContentPanel();
		panel2.setHeaderVisible(false);
		panel2.setBorders(false);
		panel2.add(this.getGrid3());
		panel2.setBottomComponent(toolBar2);
		vp3.add(this.createImport());
		vp3.add(panel2);
		
		hp.add(vp2);
		hp.add(vp3);
		ContentPanel center = new ContentPanel();
		center.setHeaderVisible(false);
		center.add(hp);
		
		ContentPanel panel = new ContentPanel();
		panel.setHeading("选择部门");
		panel.setCollapsible(true);
		panel.add(getTreePanel());
		add(panel,northData);
		add(center,centerData);
		cp.setStyleName("hp_css");//添加一个css属性
		this.layout();
	}
	
	BaseTreeStore<TreeNodeModelData> treeStore = null;
	private TreePanel<TreeNodeModelData> getTreePanel(){
		if(treepanel == null){
			initTreePanel();
		}
		return treepanel;
	}
	
	private BaseTreeStore<TreeNodeModelData> getTreeStore(){
		if (treeStore == null) {
			initTreeStore();
		}
		return treeStore;
	}
	
	private BaseTreeStore<TreeNodeModelData> initTreeStore(){
		StoreInfo info = new StoreInfo();
		String sql2 = "select icode,id,name from SystemInfo where id like "+results+" order by id asc";
		info.setSql(sql2);
		info.setTreesortcolumn("id");
		info.setKeyname(new String[]{ "icode" });
		info.setTablename("SystemInfo");
		treeStore = new BaseTreeStore<TreeNodeModelData>(info,false);
		treeStore.load();
		return treeStore;
	}
	
	private void initTreePanel(){
		treepanel = new TreePanel<TreeNodeModelData>(getTreeStore());
		treepanel.setSize(200,506);
		treepanel.setBorders(true);
		treepanel.setDisplayProperty("name");
		treepanel.setCheckStyle(CheckCascade.PARENTS);
		treepanel.setCheckNodes(CheckNodes.BOTH);
		treepanel.setCheckable(false);
		treepanel.setAutoLoad(true);
		treepanel.setCaching(true);
		treepanel.getStyle().setLeafIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.tree_file())); 
		
		treepanel.addListener(Events.OnClick,
			new Listener<TreePanelEvent<TreeNodeModelData>>() {
				public void handleEvent(TreePanelEvent<TreeNodeModelData> be) {
					String id = be.getItem().get("id").toString();
					treeDepId=id;
					treeDepName=be.getItem().get("name").toString();
					if(be.getItem().getChildCount() == 0){
						set_grid(id);
					}
				}
			});
	}
	
	public void set_grid(String id){
		StoreInfo info2 = new StoreInfo();
		info2.setTablename("hr_trainingRecord_bcode");
		info2.setKeyname(new String[] { "icode" });
		String where=" where 1=1 and ";
		if(id.length()<5){
			where=where+" sectionCode like '" +id+ "%25'";
		}else{
			where=where+" sectionCode = '" +id+ "'";
		}
		info2.setSql("select * from hr_trainingRecord_bcode "+where);//这里sql的linke %%  有问题
		
		System.out.println("sql====" + info2.getSql());
		grid2.getStore().setStoreinfo(info2);
		grid2.getStore().reload();
		grid2.getView().refresh(true);	
    }
	
	BcodeSelectDialog<TreeNodeModelData> bsd_add ;
	Button btnAdd = null;
	Button btnGrade = null;
	
	private FieldSet createAdd(){
		
		bsd_add = new BcodeSelectDialog<TreeNodeModelData>(){
			public void doposted(List<TreeNodeModelData> modeldatalist) {
				if(modeldatalist.size()>0)
				{
					String bcode_str="";
					for(int i=0;i<modeldatalist.size();i++){
						bcode_str=bcode_str+";"+modeldatalist.get(i).get("bname");
					}
					bcode_str=bcode_str.substring(1, bcode_str.length());
					this.setEmptyText(bcode_str);
				}
			}
		};
		bsd_add.setNeesreselect(true);
		bsd_add.setEmptyText("未选择数据");
		bsd_add.setCheckNodes(CheckNodes.BOTH);
		
		FieldSet addHandle = new FieldSet();
	//	addHandle.setHeading("添加操作");
		
		HorizontalPanel s = new HorizontalPanel();
		
		s.add(new Label("选择培训类型："));
		typeCode.setWidth(100);
		s.add(typeCode);
		
		s.add(new Label("选择人员:"));
		s.add(bsd_add);
		bsd_add.setWidth(100);
		btnAdd = new Button("添加");
		btnAdd.setWidth(60);
		btnAdd.addListener(Events.OnClick, getListener());
		s.add(btnAdd);
		
		btnGrade = new Button("总评定");
		btnGrade.setVisible(false);
		btnGrade.setWidth(60);
		btnGrade.addListener(Events.OnClick, getListener());
		s.add(btnGrade);
		
		addHandle.add(s);
		return addHandle;
	}
	Button btnImport = null;
	DateField trainingTime;
	DateField confirmTime;
	
	private FieldSet createImport(){
		FieldSet importHandle = new FieldSet();
	//	importHandle.setHeading("导入操作");
		HorizontalPanel s = new HorizontalPanel();
		
		s.add(new Label("培训日期:"));
		trainingTime = new DateField();
		trainingTime.setWidth(100);
		trainingTime.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		s.add(trainingTime);
		
		s.add(new Label("确定日期:"));
		confirmTime = new DateField();
		confirmTime.setWidth(100);
		confirmTime.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		s.add(confirmTime);
		
		btnImport = new Button("导入培训内容");
		btnImport.setWidth(100);
		btnImport.addListener(Events.OnClick, getListener());
		s.add(btnImport);
	
		importHandle.add(s);
		return importHandle;
	}
	
	BaseStore<BusiObject> store2 = null;
	public BaseStore<BusiObject> getStore2(){
		if(store2 == null){
			createStore2();
		}
		store2.setToolBar(toolBar1);
		store2.initcompleted();
		return store2;
	}
	
	ModelType type2 = new ModelType();
	private BaseStore<BusiObject> createStore2(){
		
		type2.setRoot("records");
		type2.setRecordName("record");
		type2.setTotalName("totle");
		
		type2.addField("icode");
		type2.getField("icode").setType(Long.class);
		
		type2.addField("trainingRecord_icode");
		type2.getField("trainingRecord_icode").setType(Long.class);
		
		type2.addField("sectionCode");
		type2.getField("sectionCode").setType(String.class);
		
		type2.addField("typeCode");
		type2.getField("typeCode").setType(String.class);
		
		type2.addField("typeName");
		type2.getField("typeName").setType(String.class);
		
		type2.addField("bcode");
		type2.getField("bcode").setType(String.class);
		
		type2.addField("insidePosition");
		type2.getField("insidePosition").setType(String.class);
		
		type2.addField("entryDate");
		type2.getField("entryDate").setType(Date.class);
		
		type2.addField("number");
		type2.getField("number").setType(Integer.class);
		
		type2.addField("grade");
		type2.getField("grade").setType(String.class);
		
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_trainingRecord_bcode");
		info.setKeyname(new String[] { "icode"});
		info.setSql("select * from hr_trainingRecord_bcode where 1 = 2");
		store2 = new BaseStore<BusiObject>(type2, info);
		return null;
	}
	
	BaseGrid grid2 = null;
	public BaseGrid getGrid2() {
		if (grid2 == null) {
			createGrid2();
		}
		return grid2;
	}
	
	private void createGrid2(){
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		
		ColumnConfig C2 = new ColumnConfig("sectionCode", "分部门", 80);
		C2.setRenderer(sectionCode);
		columns.add(C2);
		
		ColumnConfig C7 = new ColumnConfig("typeCode", "培训类型名称", 90);
		C7.setRenderer(typeRenert);
		columns.add(C7);
		
		ColumnConfig C5 = new ColumnConfig("bcode", "参培人员", 60);
		C5.setRenderer(bcode);
		columns.add(C5);
		
		ColumnConfig C6 = new ColumnConfig("insidePosition", "职务", 80);
		columns.add(C6);
		
		ColumnConfig C8 = new ColumnConfig("entryDate", "入职日期", 80);
		C8.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C8);
		
		ColumnConfig C9 = new ColumnConfig("grade", "总评定", 60);
		C9.setHidden(true);
		TextField<String> tfgrade = new TextField<String>();
		tfgrade.setName("grade");
		C9.setEditor(new CellEditor(tfgrade));
		columns.add(C9);
		
		ColumnConfig C1 = new ColumnConfig("number", "培训期数", 60);
		NumberField num = new NumberField();
		C1.setNumberFormat(NumberFormat.getFormat("00"));
		C1.setEditor(new CellEditor(num));
		columns.add(C1);
		
		ColumnModel cm = new ColumnModel(columns);
		grid2 = new BaseGrid(getStore2(), cm){
			@SuppressWarnings("unchecked")
			public void addnewrecord() {
				if (treeDepId == null || treeDepId.length() < 6) {
					MessageBox.alert("警告", "只能对小部门进行添加信息，请重新选择小部门，谢谢", null);
					return;
				}
				HashMap hp = new HashMap();
				hp.put("sectionCode", treeDepId);
				grid2.getStore().add(hp);
			}
			
			public void deleterecord(){
				int idx = 0;
				if (grid2.getSelectionModel().getSelectedItems().size() > 0) {
					idx = grid2.getStore().indexOf(
							grid2.getSelectionModel().getSelectedItem());

					grid2.getStore().remove(grid2.getStore().getAt(idx));
					idx = idx == 0 ? 0 : idx - 1;
				}
				grid2.getSelectionModel().select(idx, false);
				if(grid2.getSelectionModel().getSelectedItem() != null){
					Long icode = Long.parseLong(grid2.getSelectionModel().getSelectedItem().get("icode").toString());
					String sql = "delete from hr_trainingRecord_bcode_content where trainingRecordBcode_icode = "+icode+"";
					command(sql);
					grid3.getView().refresh(true);
				}
			}
		}
		;
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid2.setSelectionModel(cbs);
		grid2.setSize(500, 395);
		grid2.setBorders(false);
		grid2.setLoadMask(true);
	}
	
	BaseStore<BusiObject> store3 = null;
	public BaseStore<BusiObject> getStore3(){
		if(store3 == null){
			createStore3();
		}
		store3.setToolBar(toolBar2);
		store3.initcompleted();
		return store3;
	}
	
	private BaseStore<BusiObject> createStore3(){
		
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		
		type.addField("trainingRecordBcode_icode");
		type.getField("trainingRecordBcode_icode").setType(Long.class);
		
		type.addField("typeCode");
		type.getField("typeCode").setType(String.class);
		
		type.addField("content");
		type.getField("content").setType(String.class);
		
		type.addField("period");
		type.getField("period").setType(Integer.class);
		
		type.addField("teacher");
		type.getField("teacher").setType(String.class);
		
		type.addField("trainingDate");
		type.getField("trainingDate").setType(Date.class);
		
		type.addField("cofirmDate");
		type.getField("cofirmDate").setType(Date.class);
		
		type.addField("attendanced");
		type.getField("attendanced").setType(Boolean.class);
		
		type.addField("lated");
		type.getField("lated").setType(Boolean.class);
		
		type.addField("grade");
		type.getField("grade").setType(String.class);
		
		type.addField("evaluation");
		type.getField("evaluation").setType(String.class);
		
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_trainingRecord_bcode_content");
		info.setKeyname(new String[] { "icode"});
		info.setSql("select * from hr_trainingRecord_bcode_content where trainingRecordBcode_icode = '{icode}'");
		info.setParent(getStore2());
		info.setLinkparentcolumns(new String[] { "icode" }); 
		info.setLinkparent_chile_columns(new String[] { "trainingRecordBcode_icode"  });
		store3 = new BaseStore<BusiObject>(type, info);
		return null;
	}
	
	BaseGrid grid3 = null;
	public BaseGrid getGrid3() {
		if (grid3 == null) {
			createGrid3();
		}
		return grid3;
	}
	
	private void createGrid3(){
//		RpcProxy<PagingLoadResult<BusiObject>> proxy = new RpcProxy<PagingLoadResult<BusiObject>>(){
//			@Override
//			protected void load(Object loadConfig,AsyncCallback<PagingLoadResult<BusiObject>> callback) {
//				// TODO Auto-generated method stub
//			}
//			
//		};
//		final PagingLoader<PagingLoadResult<ModelData>> loader = new BasePagingLoader<PagingLoadResult<ModelData>>(proxy);  
//		loader.setRemoteSort(true);  
//	//	ListStore<Post> store = new ListStore<Post>(loader);  
//
//		final PagingToolBar toolBar = new PagingToolBar(50);  
//		toolBar.bind(loader); 
		
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		
		ColumnConfig C6 = new ColumnConfig("content", "内容", 150);
		C6.setRenderer(new GridCellRenderer<ModelData>() {              
		       public String render(ModelData model, String property, ColumnData d, int rowIndex,
		          int colIndex, ListStore<ModelData> store, Grid<ModelData> grid) {             
		    	  StringBuffer content = new StringBuffer();
		    	  content.append("<div style=\"white-space:normal; \" >");
		    	  content.append(model.<String>get("content"));
		    	  content.append("</div>");
	              return content.toString();                                                   
		      }                                                                                 
		    });
		columns.add(C6);
		
		ColumnConfig C3 = new ColumnConfig("trainingDate", "培训日期", 80);
		C3.setEditor(new CellEditor(new DateField()));
		C3.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C3);
		
		ColumnConfig C10 = new ColumnConfig("cofirmDate", "确定日期", 80);
		C10.setHidden(true);
		C10.setEditor(new CellEditor(new DateField()));
		C10.setDateTimeFormat(DateTimeFormat.getFormat("yyy-MM-dd"));
		columns.add(C10);
		
		CheckColumnConfig checkColumn = new CheckColumnConfig("attendanced", "是否参加", 60);  
		checkColumn.setHidden(false);
		CellEditor checkBoxEditor = new CellEditor(new CheckBox());  
		checkBoxEditor.setValue(true);
		checkColumn.setEditor(checkBoxEditor);  
		columns.add(checkColumn);
		
		ColumnConfig C4 = new ColumnConfig("period", "时长", 50);
		C4.setHidden(false);
		C4.setEditor(new CellEditor(new TextField<String>()));
		columns.add(C4);
		
		ColumnConfig C5 = new ColumnConfig("teacher", "讲师", 50);
		C5.setHidden(false);
		C5.setEditor(new CellEditor(new TextField<String>()));
		columns.add(C5);		
		ColumnConfig C8 = new ColumnConfig("grade", "评分", 60);
		C8.setHidden(true);
		C8.setEditor(new CellEditor(new NumberField()));
		columns.add(C8);
		
		
		ColumnConfig C7 = new ColumnConfig("evaluation", "评估", 60);
		C8.setHidden(true);
		C7.setEditor(new CellEditor(new TextField<String>()));
		columns.add(C7);
		
		ColumnModel cm = new ColumnModel(columns);
		grid3 = new BaseGrid(getStore3(), cm){
			@SuppressWarnings("unchecked")
			public void addnewrecord() {
				MessageBox.alert("提示","请使用上面的‘导入培训内容’进行数据导入，谢谢", null);
				return;
			}
		};
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid3.setSelectionModel(cbs);
		grid3.setBorders(false);
		grid3.setSize(525, 395);
		grid3.setLoadMask(true);
	}
	
	int sync = 0;                                                      
	Listener<BaseEvent> defaultlistener;                               
                                                                     
	public Listener<BaseEvent> getListener() {                                
		if(defaultlistener!=null)                                        
		{                                                                
			return defaultlistener;                                        
		}                                                                
                                                                     
		defaultlistener = new Listener<BaseEvent>() {                    
			public void handleEvent(BaseEvent be) {                        
				sync++;                                                    
				try {                                                      
					if (sync == 1) {                                   
						if (be.getType() == Events.Select) { 
							
						}else if(be.getType() == Events.OnBlur){
							
						}else if(be.getType() == Events.OnClick){
							if(be.getSource().equals(btnAdd)){
								if (treeDepId == null || treeDepId.length() <= 4) {
									MessageBox.alert("警告", "只能安排小部门的人员进行培训，请重新选择小部门，谢谢", null);
								}else if(typeCode.getValue()== null){
									MessageBox.alert("警告", "请选择培训类型后再添加新信息", null);
								}else{
									if(typeCode.getValue().get("code").toString().equals("TTD007")){
										BusiObject bo = new BusiObject();
										bo.set("sectionCode", treeDepId);
										bo.set("typeCode", typeCode.getValue().get("code"));
										bo.set("typeName", typeCode.getValue().get("name"));
										getStore2().add(bo);
									}else{
										if(bsd_add.getTree().getCheckedSelection() == null || bsd_add.getTree().getCheckedSelection().size() == 0){
											MessageBox.alert("警告", "请选择参培人员后再添加新信息", null);
										}else{
											List<TreeNodeModelData>  selectchecklist = bsd_add.getTree().getCheckedSelection();
											String bcode_str = "";
											List<String> systemId = new ArrayList<String>();
											for(final TreeNodeModelData tnmd:selectchecklist){
												if (tnmd.isLeaf()) {
													bcode_str += "'"+tnmd.get("bcode") + "',";
												} else {
													systemId.add(tnmd.get("systembcode").toString());
												}
											}
											
											String sql = "select systemid, bcode.bcode,bcode.bname,employinnertitle,entrydate from bcode,bcode_job where bcode.bcode=bcode_job.bcode and employstatus = '在职'";
											
											if (!bcode_str.equals("")) {
												bcode_str = bcode_str.substring(0, bcode_str.length()-1);
											}
											
											if (systemId.size() == 0) {
												sql +=  " and bcode.bcode in ("+bcode_str+")";
											} else {
												sql += " and (";
												for (String id : systemId) {
													sql +=  " systemid like '" + id + "%' or";
												}
												
												if (!bcode_str.equals("")) {
													sql += " bcode.bcode in ("+bcode_str+"))";
												} else {
													sql = sql.substring(0, sql.length() - 3) + ")";
												}
												
											}
											
											final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT.create(com.base.myproject.client.tools.GreetingService.class);
											   greetingService.getDataSet(sql, new AsyncCallback<DataSet>(){
												@Override
												public void onFailure(Throwable caught) {	
													MessageBox.alert("Error"," 服务器繁忙......", null);
												}
												@Override
												public void onSuccess(DataSet result) {	
													for(int i = 0;i < result.getRowCount();i++){
														BusiObject bo = new BusiObject();
														bo.set("sectionCode", result.getValue(i, "systemid"));
														bo.set("typeCode", typeCode.getValue().get("code"));
														bo.set("typeName", typeCode.getValue().get("name"));
														bo.set("bcode", result.getValue(i, "bcode"));
														bo.set("insidePosition", result.getValue(i, "employinnertitle"));
														bo.set("entryDate",dateFormat(result.getValue(i, "entrydate")));
														getStore2().add(bo);
													}
												}
											});
										}
									}
								}
							}else if(be.getSource().equals(btnImport)){
								if(grid2.getSelectionModel().getSelectedItem() == null){
									MessageBox.alert("提示","请选择左边的培训记录后再添加新信息", null);
									return;
								}
								/*
								 * 如果store3有数据了，说明已经导入过培训内容了，不能再导入了
								 */
								if (getStore3().getModels().size() > 0) {
									MessageBox.alert("提示","你已经导入了培训内容了，不需要再导入，谢谢", null);
								} else{
									final String typecode = grid2.getSelectionModel().getSelectedItem().get("typeCode").toString();
									String department = grid2.getSelectionModel().getSelectedItem().get("sectionCode").toString();
									Date trainingDate = trainingTime.getValue();
									Date confirmDate = confirmTime.getValue();
									if(trainingDate == null){
										date1 = new Date();
										date2 = new Date();
									}else {
										date1 = trainingDate;
										date2 = confirmDate;
									}
									if(typecode.equals("TTD003") || typecode.equals("TTD004")){
										String position = grid2.getSelectionModel().getSelectedItem().get("insidePosition").toString();
										String sql1 = "select content from hr_TrainingType_content where insidePosition = '"+position+"' and typeCode = '"+typecode+"' and sectionCode = '"+department+"'";
										final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
										   greetingService2.getDataSet(sql1, new AsyncCallback<DataSet>(){
											@Override
											public void onFailure(Throwable caught) {	
												MessageBox.alert("Error"," 服务器繁忙......", null);
											}
											@Override
											public void onSuccess(DataSet result) {	
												for(int i = 0;i < result.getRowCount();i++){
													BusiObject bo = new BusiObject();
													bo.set("typeCode", typecode);
													bo.set("content", result.getValue(i, "content"));
													bo.set("trainingDate", date1);
													bo.set("cofirmDate", date2);
													getStore3().add(bo);
												}
											}
										});
									}else{
										String sql2 = "select content from hr_TrainingType_content where typeCode = '"+typecode+"'";
										final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
										   greetingService2.getDataSet(sql2, new AsyncCallback<DataSet>(){
											@Override
											public void onFailure(Throwable caught) {	
												MessageBox.alert("Error"," 服务器繁忙......", null);
											}
											@Override
											public void onSuccess(DataSet result) {	
												for(int i = 0;i < result.getRowCount();i++){
													BusiObject bo = new BusiObject();
													bo.set("typeCode", typecode);
													bo.set("content", result.getValue(i, "content"));
													bo.set("trainingDate", date1);
													bo.set("cofirmDate", date2);
													getStore3().add(bo);
												}
											}
										});
									}
								}
							}else if(be.getSource().equals(btnGrade)){
								if(grid2.getSelectionModel().getSelectedItem().get("typeCode").equals("TTD002")){
									Long recordBcodeIcode = grid2.getSelectionModel().getSelectedItem().get("icode");
									String sql3 = "select round((a+b*0.5)/c,2) as result from (select (select count(icode)  from hr_trainingRecord_bcode_content" +
													" where trainingRecordBcode_icode = "+recordBcodeIcode+" "+
													"and datediff(day,trainingDate,cofirmDate) < 15 and attendanced = 1) as a,"+
													"(select count(icode)  from hr_trainingRecord_bcode_content where trainingRecordBcode_icode = "+recordBcodeIcode+"" +
													"and datediff(day,trainingDate,cofirmDate) > 15 and attendanced = 1) as b,"+
													"(select count(icode)  from hr_trainingRecord_bcode_content where trainingRecordBcode_icode = "+recordBcodeIcode+") as c) as aaa";
									final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
									   greetingService2.getDataSet(sql3, new AsyncCallback<DataSet>(){
										@Override
										public void onFailure(Throwable caught) {	
											MessageBox.alert("Error"," 服务器繁忙......", null);
										}
										@Override
										public void onSuccess(DataSet result) {	
											ModelData model = grid2.getSelectionModel().getSelectedItem();
											int row = grid2.getStore().indexOf(model);
											String value = result.getValue(0,"result");
											value = value.substring(0,value.indexOf(".") + 3);
											grid2.getStore().setValue(row, "grade",value);
										}
									});
								}else if(grid2.getSelectionModel().getSelectedItem().get("typeCode").equals("TTD009")){
									Long recordBcodeIcode = grid2.getSelectionModel().getSelectedItem().get("icode");
									String sql3 = "select round(a/8,2) as result from(select (select sum(grade) from hr_trainingRecord_bcode_content where trainingRecordBcode_icode = "+recordBcodeIcode+") as a)as b";
									final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
									   greetingService2.getDataSet(sql3, new AsyncCallback<DataSet>(){
										@Override
										public void onFailure(Throwable caught) {	
											MessageBox.alert("Error"," 服务器繁忙......", null);
										}
										@Override
										public void onSuccess(DataSet result) {	
											ModelData model = grid2.getSelectionModel().getSelectedItem();
											int row = grid2.getStore().indexOf(model);
											String value = result.getValue(0,"result");
											value = value.substring(0,value.indexOf(".") + 3);
											grid2.getStore().setValue(row, "grade",value);
										}
									});
								}
							}else if(be.getSource().equals(grid2)){
								if(grid2.getSelectionModel().getSelectedItem() != null){
									String typecode = grid2.getSelectionModel().getSelectedItem().get("typeCode");
									if(typecode.equals("TTD001")){
										grid3.getColumnModel().setHidden(3, false);
										grid3.getColumnModel().setHidden(4, true);
										grid3.getColumnModel().setHidden(5, false);
										grid3.getColumnModel().setHidden(6, false);
										grid3.getColumnModel().setHidden(7, false);
										grid3.getColumnModel().setHidden(8, true);
										grid3.getColumnModel().setHidden(9, true);
										grid2.getColumnModel().setHidden(7, true);
										grid2.getColumnModel().setHidden(4, false);
										grid2.getColumnModel().setHidden(5, false);
										grid2.getColumnModel().setHidden(6, false);
										grid2.getColumnModel().setHidden(8, false);
										btnGrade.setVisible(false);
									}else if(typecode.equals("TTD002")){
										grid3.getColumnModel().setHidden(3, false);
										grid3.getColumnModel().setHidden(4, false);
										grid3.getColumnModel().setHidden(5, false);
										grid3.getColumnModel().setHidden(6, false);
										grid3.getColumnModel().setHidden(7, false);
										grid3.getColumnModel().setHidden(8, true);
										grid3.getColumnModel().setHidden(9, true);
										grid2.getColumnModel().setHidden(7, false);
										grid2.getColumnModel().setHidden(4, false);
										grid2.getColumnModel().setHidden(5, false);
										grid2.getColumnModel().setHidden(6, false);
										grid2.getColumnModel().setHidden(8, false);										
										btnGrade.setVisible(true);
									}else if(typecode.equals("TTD003") || typecode.equals("TTD004")){
										grid3.getColumnModel().setHidden(3, false);
										grid3.getColumnModel().setHidden(4, true);
										grid3.getColumnModel().setHidden(5, false);
										grid3.getColumnModel().setHidden(6, false);
										grid3.getColumnModel().setHidden(8, true);
										grid3.getColumnModel().setHidden(9, false);
										grid2.getColumnModel().setHidden(4, false);
										grid2.getColumnModel().setHidden(5, false);
										grid2.getColumnModel().setHidden(6, false);
										grid2.getColumnModel().setHidden(7, false);
										grid2.getColumnModel().setHidden(8, false);
										btnGrade.setVisible(true);
									}else if(typecode.equals("TTD009")){
										grid3.getColumnModel().setHidden(3, false);
										grid3.getColumnModel().setHidden(4, true);
										grid3.getColumnModel().setHidden(5, false);
										grid3.getColumnModel().setHidden(6, true);
										grid3.getColumnModel().setHidden(7, true);
										grid3.getColumnModel().setHidden(8, false);
										grid3.getColumnModel().setHidden(9, true);
										grid2.getColumnModel().setHidden(7, true);
										grid2.getColumnModel().setHidden(4, false);
										grid2.getColumnModel().setHidden(5, false);
										grid2.getColumnModel().setHidden(6, false);
										grid2.getColumnModel().setHidden(8, false);
										btnGrade.setVisible(false);
									}else if(typecode.equals("TTD007")){
										grid3.getColumnModel().setHidden(3, false);
										grid3.getColumnModel().setHidden(4, true);
										grid3.getColumnModel().setHidden(5, false);
										grid3.getColumnModel().setHidden(6, true);
										grid3.getColumnModel().setHidden(7, true);
										grid3.getColumnModel().setHidden(8, false);
										grid3.getColumnModel().setHidden(9, true);
										grid2.getColumnModel().setHidden(4, true);
										grid2.getColumnModel().setHidden(5, true);
										grid2.getColumnModel().setHidden(6, true);
										grid2.getColumnModel().setHidden(7, false);
										grid2.getColumnModel().setHidden(8, true);
										btnGrade.setVisible(false);
									}else{
										grid3.getColumnModel().setHidden(3, true);
										grid3.getColumnModel().setHidden(4, true);
										grid3.getColumnModel().setHidden(5, false);
										grid3.getColumnModel().setHidden(6, true);
										grid3.getColumnModel().setHidden(7, true);
										grid3.getColumnModel().setHidden(8, true);
										grid3.getColumnModel().setHidden(9, true);
										grid2.getColumnModel().setHidden(4, false);
										grid2.getColumnModel().setHidden(5, false);
										grid2.getColumnModel().setHidden(6, false);
										grid2.getColumnModel().setHidden(7, false);
										grid2.getColumnModel().setHidden(8, false);
										btnGrade.setVisible(true);
									}
								}
							}
						}                                          
					}                                                  
				} finally {                                                
					sync--;                                            
				}                                                          
			}                                                              
		};                                                               
		return defaultlistener;                                          
	}
	public Date dateFormat(String date){
		Date df_date = new Date();
		String[] strdates = date.split("-");
		int year = Integer.parseInt(strdates[0]);
		int month = Integer.parseInt(strdates[1]);
		int day = Integer.parseInt(strdates[2].substring(0,2));
		df_date.setYear(year-1900);
		df_date.setMonth(month-1);
		df_date.setDate(day);
		return df_date;
	}
	
	private boolean  command(String sql){
		CommandSyncsql csql = new CommandSyncsql();//执行sql命令
		String delsql =sql;
		csql.getV().add(delsql);
		if(csql.getV().size()<=0){
			return false;
		}else{
			CommandSyncContainer list = new CommandSyncContainer();//可以添加的命令
			 list.add(csql);
		
			 GreetingServiceAsync greetingService = GWT
				.create(GreetingService.class);
			 greetingService
				.SendCommandSync(
						list,
						new AsyncCallback<CommandSyncReturnObject>() {
							@Override
							public void onFailure(
									Throwable caught) {
								MessageBox.alert("错误",
										"网络连接失败", null);
							}
							@Override
							public void onSuccess(
									CommandSyncReturnObject result) {
								if (result.isB()) {
									Info.display("提示信息", "添加成功");								
								}
								else{
									MessageBox.alert("错误",
											"错误，错误代码"+result.getMessage(), null);
									
								}
							}
						});
		}
		return true;
	}
	
	
}
